package net.chrone.quickpayapi.util;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;



/**
 * Socket客户端
 * Jerry
 */
public class SocketClient {
	
	private static Logger logger = LoggerFactory.getLogger(SocketClient.class);
	
	private static final int CONNECT_TIMEOUT = 60 * 1000; // mini seconds
    private static final int READ_TIMEOUT = 60 * 1000; // mini seconds
    
    /**
     * 用socket往服务端发送报文
     * @param ip：服务端IP
     * @param port：服务端端口
     * @param str：带发送报文信息
     * @param charSet：字符编码
     * @param packLen：包头长度
     * @return
     */
	public static byte[] send2UMS(byte[] data){
			Socket socket = new Socket();
			SocketAddress address = new InetSocketAddress(SdkUtil.getStringValue("umsIP"), Integer.valueOf(SdkUtil.getStringValue("umsPort")));
			logger.info("准备发送报文，IP="+SdkUtil.getStringValue("umsIP")+",PORT="+SdkUtil.getStringValue("umsPort"));
			try {
				socket.connect(address, CONNECT_TIMEOUT);
				socket.setSoTimeout(READ_TIMEOUT);
				OutputStream os = socket.getOutputStream();
				InputStream is = socket.getInputStream();
				BufferedInputStream inputStream = new BufferedInputStream(is);
				os.write(data);
				os.flush();
				byte[] inPackLen = new byte[2];
				inputStream.read(inPackLen);
				int lengthInStr = Integer.parseInt(BcdUtil.bcd2str(inPackLen),16);
				byte[] inBytes = new byte[lengthInStr];
				inputStream.read(inBytes);
				inputStream.close();
				return inBytes;
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					socket.close();
				} catch (IOException e) {
					logger.error("socket 关闭发生异常"+e.getMessage());
				}
			}
			return null;
	}
	
}
